package com.chapter03;

import com.bdqn.util.JDBCUtils;
import com.pojo.Grade;

import java.lang.reflect.Field;
import java.sql.*;

public class Test08_TestQuery {
    public static void main(String[] args) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchFieldException {
        Connection connection = JDBCUtils.getConnection();

        String sql = "SELECT gradeId,gradeName FROM grade;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();

        // ResultSet的元数据
        ResultSetMetaData rsmd = resultSet.getMetaData();
        int columnCount = rsmd.getColumnCount();
        //System.out.println(columnCount);//查询列的数量

        for (int i = 0; i < columnCount; i++) {
            System.out.print(rsmd.getColumnLabel(i + 1)+"\t");// 能够拿到每一列的列名
        }
        System.out.println();

        Class<?> gradeClazz = Class.forName("com.pojo.Grade");

        while (resultSet.next()) {

            // 通过反射的方式创建了一个grade对象
            Grade grade = (Grade)gradeClazz.newInstance();

            for (int i = 0; i < columnCount; i++) {
                // 拿到每一列的值
                Object objValue = resultSet.getObject(i + 1);
                // 可以拿到列的名称
                String columnLabel = rsmd.getColumnLabel(i + 1);

                // 拿到一个字段
                Field field = gradeClazz.getDeclaredField(columnLabel);
                field.setAccessible(true);
                field.set(grade,objValue);
            }
            System.out.println(grade);
//            System.out.println();
//            Grade grade = new Grade();
//            grade.setGradeId(resultSet.getInt(1));
//            grade.setGradeName(resultSet.getString(2));
//            System.out.println(grade);
        }

        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
